import Vue from 'vue'
import store from '@/store'
import { isString } from '@web-utils/core'

async function handler(error, vm, info) {
  await Vue.nextTick()
  let type
  let message
  let stack

  if (isString(error)) {
    type = 'warn'
    message = error
    stack = info
  } else {
    type = 'error'
    message = error.message || error
    stack = error.stack || error
  }
  store.commit('logs/addLog', { type, message, stack, info })
  if (process.env.NODE_ENV === 'development') {
    console.groupCollapsed(message)
    console[type](stack)
    console.groupEnd()
  }
}

export default {
  install(Vue) {
    Vue.config.warnHandler = handler
    Vue.config.errorHandler = handler
  }
}
